<template>
  <div>
    <el-dialog v-model="props.dialogVisible" :title="newTitle" draggable width="800" :before-close="handleServiceClose">
      <el-form :inline="true" :model="submitFrom" label-width="auto" ref="ServerRef" :rules="rules"
        label-position="left">
        <el-form-item label="服务器编号" prop="serverNo" style="width: 100%" required>
          <el-input v-model.trim="submitFrom.serverNo" placeholder="请输入" :maxlength="32" />
        </el-form-item>

        <el-form-item label="服务商" prop="cloudServerProviderId" style="width: 100%" required>
          <el-select v-model="submitFrom.cloudServerProviderId" placeholder="请选择" @change="changeProvider">
            <el-option v-for="dict in sys_provider" :key="dict.value" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务商账号" style="width: 100%" prop="cloudServerId" required>
          <el-select v-model="submitFrom.cloudServerId" placeholder="请选择">
            <el-option v-for="dict in sys_account" :key="dict.value" :label="dict.username"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家" style="width: 100%" prop="countryId" required>
          <el-tree-select @change="changeDistrict" v-model="submitFrom.countryId" placeholder="请选择" :data="sys_country"
            :props="defaultProps" />
        </el-form-item>
        <el-form-item label="城市" style="width: 100%" prop="countryZoneId" required>
          <el-select v-model="submitFrom.countryZoneId" placeholder="请选择">
            <el-option v-for="dict in sys_district" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" style="width: 100%" prop="serverAccount" required>
          <el-input v-model.trim="submitFrom.serverAccount" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="密码类型" style="width: 100%" prop="pwdType" :required="!showPwd" v-if="!showPwd">
          <el-radio-group v-model="submitFrom.pwdType" @change="changePwd" :disabled="showPwd">
            <el-radio value="pwd">密码</el-radio>
            <el-radio value="secretKey">密钥</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" style="width: 100%" prop="serverPassword" :required="processing()" v-if="isDisplay()">
          <el-input v-model.trim="submitFrom.serverPassword" placeholder="请输入" show-password type="password"
            :disabled="showPwd" />
        </el-form-item>
        <el-form-item label="密钥" style="width: 100%" prop="serverSecretKey"
          :required="submitFrom.pwdType == 'secretKey' ? true : false" v-if="submitFrom.pwdType == 'secretKey'">
          <el-input v-model.trim="submitFrom.serverSecretKey" placeholder="请输入" show-password type="textarea"
            :autosize="{ minRows: 5 }" :disabled="showSecret && submitFrom.serverSecretKey" />
        </el-form-item>
        <el-form-item label="加载本地密钥" style="width: 100%" v-if="submitFrom.pwdType == 'secretKey'">
          <el-upload class="upload-demo" drag action="#" multiple :before-upload="handleBeforeUpload" :limit="1"
            :on-exceed="handleExceed">
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">只能上传{{ sys_fileType.join("/") }} 文件</div>
            </template>
          </el-upload>
        </el-form-item>


        <el-form-item label="开始时间" style="width: 100%" required prop="newInitiate">
          <el-date-picker v-model="submitFrom.newInitiate" type="datetime" placeholder="请选择" style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" @change="initiateTime" />
        </el-form-item>
        <el-form-item label="到期时间" style="width: 100%" required prop="newExpire">
          <el-date-picker v-model="submitFrom.newExpire" placeholder="请选择" style="width: 100%" type="datetime"
            format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="pickerOptions" />
        </el-form-item>
        <el-form-item label="当前状态" style="width: 100%" prop="status" required>
          <el-switch :width="58" v-model="submitFrom.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt />
        </el-form-item>

        <el-form-item label="备注" style="width: 100%" prop="remark">
          <el-input maxlength="300" show-word-limit type="textarea" placeholder="请输入" :rows="7" resize="none"
            v-model.trim="submitFrom.remark"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleServiceClose">取消</el-button>
          <el-button type="primary" @click="handleServiceSure(ServerRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>





    <el-dialog v-model="showPassword" title=" " draggable width="20%" @close="handleShowPwdClose">
      <el-form :inline="true" :model="submitShowFrom" label-width="auto" ref="ShowPwdRef" :rules="rules"
        label-position="left">
        <el-form-item label="" style="width: 100%" prop="username">
          <el-input size="large" auto-complete="off" placeholder="请输入用户名" v-model.trim="submitShowFrom.username">
            <template #prefix><svg-icon icon-class="user" /></template></el-input>
        </el-form-item>
        <el-form-item prop="password" style="width: 100%">
          <el-input v-model.trim="submitShowFrom.password" type="password" size="large" auto-complete="off"
            placeholder="密码">
            <template #prefix><svg-icon icon-class="password" /></template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button style="width: 100%;" type="primary" @click="handleShowPwdSure">
          确定
        </el-button>
      </template>
    </el-dialog>







  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, reactive } from "vue";
const emits = defineEmits(["handleServiceClose", "handleServiceSure"]);
const { proxy } = getCurrentInstance();
const sys_fileType = reactive(['txt', "text", "key", "pem"])
const newTitle = ref("新增"); //名称
const ServerRef = ref(null);
const sys_provider = ref([]); //服务商
const sys_account = ref([]); //服务商账号
const sys_country = ref([]); //国家
const sys_district = ref([]); //地区
const showPassword = ref(false)//查看密码
const showPwd = ref(true)//查看密码
const showSecret = ref(true)//查看密钥



const submitFrom = ref({
  serverNo: "", //服务器编号
  cloudServerProviderId: null, //服务商
  cloudServerId: null, //服务商账号
  countryId: null, //国家
  countryZoneId: null, //地区
  pwdType: "pwd", //密码类型
  serverAccount: '',//用户名
  serverPassword: null,//密码
  serverSecretKey: null,//密钥
  startTime: null, //开始时间
  expireTime: null, //到期时间
  status: 1, //状态
  remark: "", //备注信息

  newInitiate: "",
  newExpire: "",
}); //参数
const submitShowFrom = ref({
  id: null,
  username: '',
  password: ''
}); //参数


const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  // 传值数据对象
  listItem: {
    type: Object,
    default: {},
  },
});
onMounted(() => {
  getSet();
});
watch(
  () => props.dialogVisible,
  () => {
    if (!props.dialogVisible) return;
    if (Object.keys(props.listItem).length) {
      newTitle.value = "编辑";
      getDetails(props.listItem); //获取详情
      showPwd.value = true

    } else {
      newTitle.value = "新增";
      submitFrom.value.newInitiate = proxy.getCurrent();
      showPwd.value = false
    }
  }
);
// 确定事件
const handleServiceSure = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      submitFrom.value.startTime = proxy.convertTime(
        1,
        submitFrom.value.newInitiate
      );
      submitFrom.value.expireTime = proxy.convertTime(
        1,
        submitFrom.value.newExpire
      );
      if (newTitle.value === "新增") {
        site.general
          .siteserverAdd({
            data: submitFrom.value,
          })
          .then((res) => {
            if (res.code === 200) {
              emits("handleServiceSure");
              assemble()
              proxy.$modal.msgSuccess(`新增成功`);
            }
          });
      } else {
        submitFrom.value.pwdType = ''
        site.general
          .siteserverUpdatebyid({
            pathParams: {
              id: props.listItem.id,
            },
            data: {
              ...submitFrom.value,
              updatePassword: false
            },
          })
          .then((res) => {
            if (res.code === 200) {
              emits("handleServiceSure");
              assemble()

              proxy.$modal.msgSuccess(`修改成功`);
            }
          });
      }
    }
  });
};

const handleShowPwd = () => {//显示弹出框
  showPassword.value = true
}
const handleShowPwdSure = () => {
  proxy.$refs["ShowPwdRef"].validate((valid, fields) => {
    if (!valid) return
    submitShowFrom.value.id = props.listItem.id
    if (submitFrom.value.pwdType === 'pwd') {
      site.general.siteserverViewpassword({
        data: submitShowFrom.value
      }).then((res) => {
        if (res.code === 200) {
          showPassword.value = false
          submitFrom.value.serverPassword = res.data.password
          showPwd.value = false
        }
      });
    } else {
      site.general.siteserverViewsecretkey({
        data: submitShowFrom.value
      }).then((res) => {
        if (res.code === 200) {
          showPassword.value = false
          submitFrom.value.serverSecretKey = res.data.password
          showSecret.value = false
        }
      })
    }
  })
}
const handleShowPwdClose = () => {//取消显示框
  proxy.resetForm("ShowPwdRef");
  showPassword.value = false
  submitShowFrom.value = {
    id: null,
    username: '',
    password: ''
  }
}



// 取消事件
const handleServiceClose = () => {
  emits("handleServiceClose");

  assemble()

};
const assemble = () => {
  proxy.resetForm("ServerRef");
  submitFrom.value.serverSecretKey = ''
  submitFrom.value.serverPassword = ''
  showPassword.value = false
  showSecret.value = false
  showPwd.value = false
}
const changeDistrict = (id) => {
  submitFrom.value.countryZoneId = null;
  districtList(id);
};
const getSet = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {}

  };
  // 服务商
  site.general
    .siteserverproviderList({
      data: from,
    })
    .then((res) => {
      sys_provider.value = res.data;
    });
  getCountry(from);
};
/** 查询类别管理列表 */
const getCountry = async (from) => {
  site.country
    .countryList({
      data: from,
    })
    .then((res) => {
      res.data = addLevelToTree(res.data);
      // console.log(res.data);
      sys_country.value = res.data;
    });
};
const addLevelToTree = (tree, parentLevel = 0) => {
  return tree.map((item) => ({
    ...item,
    newId: `${item.id}-${parentLevel + 1}`,
    children: item.children
      ? addLevelToTree(item.children, parentLevel + 1)
      : undefined,
  })
  )
}
const getDetails = (item) => {
  site.general
    .siteserverGetbyid({
      pathParams: {
        id: item.id,
      },
    })
    .then((res) => {
      districtList(res.data.countryId);
      submitFrom.value.serverNo = res.data.serverNo;
      submitFrom.value.cloudServerProviderId = res.data.cloudServerProviderId;
      submitFrom.value.cloudServerId = res.data.cloudServerId;
      submitFrom.value.countryId = res.data.countryId;
      submitFrom.value.countryZoneId = res.data.countryZoneId;
      submitFrom.value.serverAccount = res.data.serverAccount;
      // submitFrom.value.serverPassword = res.data.serverPassword;//密码内容
      // submitFrom.value.serverSecretKey = res.data.serverSecretKey ? res.data.serverSecretKey : null;//密钥内容
      // submitFrom.value.pwdType = res.data.pwdType;//密码类型

      submitFrom.value.newInitiate = proxy.DateTime(res.data.startTime);
      submitFrom.value.newExpire = proxy.DateTime(res.data.expireTime);
      submitFrom.value.remark = res.data.remark;
      submitFrom.value.status = res.data.status;
      getAccount(res.data.cloudServerProviderId);
    });
};
const districtList = (id) => {
  site.CountryZone.countryzoneList({
    data: {
      id: id,
    },
  }).then((res) => {
    sys_district.value = res.data;
  });
};
const getAccount = (id) => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      providerId: id,
    },
  };
  site.general
    .sitecloudserverList({
      data: from,
    })
    .then((res) => {
      sys_account.value = res.data;
    });
}
var defaultProps = reactive({
  children: "children",
  label: "description",
  value: "id", // 指定 id 作为 value 属性
});
// 选择服务商调取服务商账号
const changeProvider = (id) => {
  submitFrom.value.cloudServerId = null;
  getAccount(id)
};
const changePwd = (e) => {
  if (e === 'pwd') {
    submitFrom.value.serverSecretKey = null
  } else {
    submitFrom.value.serverPassword = null
  }
}
const processing = () => {
  if (showPwd.value) {
    return false
  } else {
    return submitFrom.value.pwdType == 'pwd' ? true : false
  }
}
const isDisplay = () => {
  if (showPwd.value) {
    return submitFrom.pwdType == 'pwd'
  } else {
    return false
  }
}

const rules = reactive({
  serverNo: [{ required: true, message: "请输入", trigger: "blur" }],
  cloudServerProviderId: [
    { required: true, message: "请选择", trigger: "blur" },
  ],
  cloudServerId: [{ required: true, message: "请选择", trigger: "blur" }],
  countryId: [{ required: true, message: "请选择", trigger: "blur" }],
  countryZoneId: [{ required: true, message: "请选择国家", trigger: "blur" }],
  newInitiate: [{ required: true, message: "请选择", trigger: "blur" }],
  newExpire: [{ required: true, message: "请选择", trigger: "blur" }],
  serverPassword: [{ required: true, message: "请输入", trigger: "blur" }],
  serverSecretKey: [{ required: true, message: "请输入", trigger: "blur" }],
  serverAccount: [{ required: true, message: "请输入", trigger: "blur" }],
  username: [{ required: true, message: "请输入", trigger: "blur" }],
  password: [{ required: true, message: "请输入", trigger: "blur" }],
});
// 开始时间选择事件
const initiateTime = (data) => {
  console.log(data);
  // 开始时间>到期时间
  if (!submitFrom.value.newExpire) return
  if (proxy.convertTime(1, data) > proxy.convertTime(1, submitFrom.value.newExpire)) return submitFrom.value.newExpire = ''//到期时间滞空
}
const pickerOptions = (data) => {
  let initiate = new Date(submitFrom.value.newInitiate).getTime();
  let newDate = new Date(data).getTime();
  return initiate > newDate
}
const handleBeforeUpload = (file) => {
  if (handelFileType(file.name)) return proxy.$modal.msgWarning(`文件格式不正确, 请上传${fileType.join("/")}文件!`);
  const isLt = file.size / 1024 / 1024 < 1;
  if (!isLt) return proxy.$modal.msgWarning(`文件大小不能超过1MB}文件!`);
  const fileReader = new FileReader();
  fileReader.onload = (e) => {
    submitFrom.value.serverSecretKey = e.target.result
  }
  fileReader.onerror = () => {
    proxy.$modal.msgWarning(`上传失败，请检查文件类型`);
  };
  fileReader.onerror = (err) => {
    proxy.$modal.msgWarning(`文件读取失败：${err}`);
  };
  fileReader.readAsText(file); // 使用 ArrayBuffer 处理二进制数据
}
// 文件个数超出
const handleExceed = () => {
  proxy.$modal.msgError(`上传文件数量不能超过 1 个!`);
}
const handelFileType = (name) => {
  return !sys_fileType.includes(name.split('.')[1].toLowerCase()) ? true : false;
}
</script>
<style lang="scss" scoped>
.upload-demo {
  width: 100%;
}
</style>